import config from "../config/config.js";
import { getCache } from "@/util/index.js";
	
function requestInterceptor(cfg) {
	return getCache('token').then((res) => {
		return Object.assign(cfg, {
			header: {
				'XX-Token': res,
				'XX-Device-Type': 'wxapp'
			}
		});
	});
};

function responseInterceptor(resPromise, option) {
	return resPromise.then(([errMsg, res]) => {
		console.warn('responseInterceptor-00', errMsg, res);
		if (!res) {
			res = {};
		} else if (errMsg === 'request:fail') {
			res = {};
		}
		const { cookie, data: { data, code, msg } = {}, errMsg: erMsg, header, statusCode } = res;
		console.warn('responseInterceptor-01', cookie, data, msg, header, statusCode, code, msg);
		if (code === 1) {
			return data;
		}
		if (option.showToast) {
			uni.showToast({
				title: msg
			});
		}
		return Promise.reject({
			code,
			msg
		});
	});
};

function send(configPromise) {
	return configPromise.then((config) => {
		return uni.request(config);
	});
}

export function get(url, param, httpOption = {}, option = { showToast: false }) {
	const cfg = {
	    url: `${config.apiHost}/${url}`,
		data: param,
		timeout: 5e3,
		...httpOption
	};
	return responseInterceptor(send(requestInterceptor(cfg)), option);
}

export function post(url, param, httpOption = {}, option = { showToast: false }) {
	const cfg = {
	    url: `${config.apiHost}/${url}`,
		data: param,
		method: 'POST',
		timeout: 5e3,
		...httpOption
	};
	return responseInterceptor(send(requestInterceptor(cfg)), option);
}